<template>
  <div>
    <van-nav-bar fixed title="理疗师" />
    <div class="has-top">
      <!-- 头部定位搜索导航组件 -->
      <physio-search
        type="primary"
        :location-city="locationCity.Name"
        :val="val"
        :areaShow="false"
				:placeholder="placeholder"
        @showAreaSelect="showAreaSelect"
        @search="search"
      />
      <!-- <div class="ml-24 pt-12 flex-v-c tab">
        <div v-for="(item,index) in tabs" :key="index" :class="{'active':tabsIndex==index}" @click="tabChange(index)">{{item.value}}</div>
      </div> -->
			
			<van-list v-if="artificerList && artificerList.length > 0" v-model="isLoading" :finished="finished" finished-text="没有更多了" :immediate-check="false" >
				<div class="pb-100">
					<div v-for="(item,index) in artificerList" :key="index" class="mlr-24 mt-24 fs-24 bg-white br-24 pd-24 van-clearfix">

						<div class="physio">
							<div class="flex">
							<div class="avator" @click="showAvatar(item.Photo)">
								<div v-if="item.StarLevel == 5 && item.Satisfaction >= 99" class="avars">
									<img class="champimg" src="@/assets/images/physio/champion.png" />
									<img class="champion" src="@/assets/images/physio/champion.gif" />
									<img-box class="avatar" :isBr50="isBr50" :img-url="item.Photo" />
								</div>
								<div v-else class="avar" @click="showAvatar(item.Photo)">
									<img-box class="classImg" :isBr50="isBr50" :img-url="item.Photo" />
								</div>
								<div class="serve">{{ item.BookStateName }}</div>
							
							</div>
							<div class="usermsg">
								<div class="user">
									<span class="username" :title="item.Name">{{ item.Name }}</span>
									<img v-if="item.StarLevel == 5 && item.Satisfaction >= 95" src="@/assets/images/physio/quality.png" />
									<img v-if="item.Punctuality >= 98" src="@/assets/images/physio/run.png" />
									<p class="lifephoto" @click="showPhoto(item.Photos)">生活照</p>
								</div>
                <div class="storemsg">
									<div class="evanum" @click="goStore(item.UserId)"><img class="item-icon" src="@/assets/images/physio/store.png" /><div class="storename">{{ item.DisStoreName }}</div></div> 
									<!-- <div class="evanum" @click="goEvaluation(item.UserId)"><img class="item-icon" src="@/assets/images/physio/comment.png" /><div>{{ item.CommentCount }}</div></div>  -->
								</div>
								<div class="color-gray7 flex">订单量 {{ item.FinishOrderCount }}　好评率 {{ item.Satisfaction }}%　<div class="evanum" @click="goEvaluation(item.UserId)"><img class="item-icon" src="@/assets/images/physio/comment.png" /></div></div>
								<!-- <div class="storemsg">
									<div class="evanum" @click="goStore(item.UserId)"><img class="item-icon" src="@/assets/images/physio/store.png" /><div class="storename">{{ item.DisStoreName }}</div></div> 
									<div class="evanum" @click="goEvaluation(item.UserId)"><img class="item-icon" src="@/assets/images/physio/comment.png" /><div>{{ item.CommentCount }}</div></div> 
								</div> -->
								<div class="color-gray7 fs-22" v-if="item.SelfIntroduce">{{ item.SelfIntroduce }}</div>
								<div class="address"><img  src="@/assets/images/physio/address.png" />{{ item.Distance!==0? item.Distance.toFixed(2) : '0'}}KM</div>
							</div>
							</div>
							<div class="markorder"  v-if="item.BookStateName != '不可预约'">
								<div class="restime color-black2">
									<div class="reducible">可约时间</div>
									<div class="time"> {{ item.NextBookTime }}</div>
								</div>
                <a class="btn" :href="'tel:' + item.Tel">立即预约</a>
								<!-- <button class="btn"  @click.stop="goDetail(item)">立即预约</button> -->
							</div>
							<div v-else></div>
						</div>
					</div>
				</div>
				
			</van-list>
			<div v-else>
				<div class="data-empty">
					<img class="img" src="@/assets/images/wealthManage/empty.png">
					<div class="text">~ 暂无数据 ~</div>
				</div>
			</div>
			
			<van-popup v-model="showPhotos" class="photos">
				<van-swipe class="my-swipe media-box" indicator-color="white" loop>
					<van-swipe-item v-for="(item, index) in Photos" :key="index" >
						<van-icon name="cross popup-close" size="23" @click="showPhotos = false" />
						<img-box class="shop-bg-box z-inner pos-r" :img-url="item" />
					</van-swipe-item>
				</van-swipe>
			</van-popup>
			<van-popup v-model="showAvatars" class="photos">
				<van-swipe class="my-swipe media-box" indicator-color="white" loop>
					<van-swipe-item>
						<van-icon name="cross popup-close" size="23" @click="showAvatars = false" />
						<img-box class="shop-bg-box z-inner pos-r" :img-url="Avatar" />
					</van-swipe-item>
				</van-swipe>
			</van-popup>

      <!-- 定位地址选择组件 -->
      <area-select
        v-show="AreaSelect"
        class="animated"
        :class="{ slideInRight: animated == 'slideIn', slideOutRight: animated == 'slideOut' }"
        :current-city="locationCity"
        @closeAreaSelect="closeAreaSelect"
        @selCity="selCity"
        @getCurrentPosition="getCurrentPosition"
      />
    </div>
		<!-- <tabBar /> -->
  </div>
</template>

<script>
import tabBar from 'components/physio/tabBar.vue'
import imgBox from 'components/imgBox'
import physioSearch from 'components/physioSearch'
import areaSelect from 'components/areaSelect'
import bussinessItem from 'components/bussinessItem'
import noData from 'components/noData'
import { GetStorePage,  GetCityIdByCode, GetUserCityId } from 'api/store'
import { GetArtificerPage } from 'api/physio'
import { format } from 'path'
import utils from 'utils/utils'

export default {
  components: {
    imgBox,
    physioSearch,
    areaSelect,
    bussinessItem,
    noData,
		tabBar
  },
  data() {
    return {
      val: '',
      locationCity: {
        ID: 0,
        Name: '定位中...'
      },
      // 初始化定位flag
      locationInit: false,
      AreaSelect: false,
      tabs: [
          {
              value: '推荐',
              id: 1
          },
          {
							value: '跑得较快',
              id: 2
          },
          {
							value: '离我最近',
              id: 3
          },
          {
							value: '我的收藏',
              id: 4
          }
      ],
      tabsIndex: 0,

      // 商家列表
      artificerList: [],

      // 下拉刷新
      isLoading: false, // 加载load
      finished: false, // 无更多数据
      isRefresh: false,
      animated: '',
      storeTypeList: [],
      // 允许列表加载(在定位成功或失败后设置true)
      listLoad: false,

      // 滚动状态
      totalAmout: 0,
      scollRequest: true,
      end: false,
			recommendCondition:{
				IsNeedPosition:0,
				orderBy: 1,
			},
			isBr50: true, //用来判断图片圆形
			showPhotos: false, //生活照弹窗
			Photos: [], //生活照列表
			placeholder: '请输入您要搜索的理疗师',
			Avatar: '',
			showAvatars: false,
    }
  },
  beforeCreate () {
  	  // 例如设置为红色
      document.querySelector('body').setAttribute('style', 'background-color: #F2F3FC;')
  },
  beforeDestroy () {
      document.querySelector('body').removeAttribute('style')
  },
  mounted() {
    this.$nextTick(function() {
      window.addEventListener('scroll', this.onScroll)
    })
  },
  created() {
		const self = this		

    const _query = this.$route.query
    if (_query && _query.storeName && _query.storeName !== 'undefined' && _query.storeName !== undefined) {
      this.val = _query.storeName
      this.recommendCondition.Name = _query.storeName
    }
    
    // 获取定位
    this.getPosition()
		//this.artificerList = []
    //// 获取筛选标签
    //this.GetStorePage()
  },
  activated() {
    this.scollRequest = true
  },
  methods: {
    goDetail(item) {
      this.scollRequest = false 
			// this.$router.push({
      //    path: '/physioTechnicianDetail',
			// 	 query: {
      //       userId: item.UserId,
      //       id: item.ID,
			// 			distance: item.Distance.toFixed(2)
      //   	}
      //  })
      window.location.href = "tel://" + item.Tel;
    },
    // 定位
    getPosition() {
      // 获取当前城市（缓存）
      const _str = localStorage.getItem('SelectCity')
			console.log(_str)
      if (_str) {
        const _obj = JSON.parse(_str)
        this.locationCity.Name = _obj.Name
        this.locationCity.ID = _obj.ID
        this.recommendCondition.areaId = _obj.ID
        // 获取经纬度缓存
        const _GeolocationData = localStorage.getItem('GeolocationData')
        if (_GeolocationData) { // 存在定位缓存
          const _GeolocationObj = JSON.parse(_GeolocationData)
          if (_GeolocationObj.center && _GeolocationObj.center.length > 0) {
            this.recommendCondition.Lng = _GeolocationObj.center[0]
            this.recommendCondition.Lat = _GeolocationObj.center[1]
          } else if (_GeolocationObj.position) {
            this.recommendCondition.Lng = _GeolocationObj.position.lng
            this.recommendCondition.Lat = _GeolocationObj.position.lat
          }
          this.listLoad = true
          this.isRefresh = true
          this.onRefresh()
        } else {
          // 调用定位获取经纬度
          this.getCurrentPosition(_obj.Name)
        }
      } else {
        this.GetUserCityId()
      }
    },
    // 下拉刷新
    onRefresh() {
      if (this.listLoad) {
        this.isRefresh = true
        this.end = false
        this.recommendCondition.PageIndex = 1
        this.artificerList = []
        this.GetStorePage()				
        this.listLoad = false  
      } else {
        this.isLoading = false
      }
    },
    // 列表刷新后的回调
    listRefresh() {
      this.isRefresh = false
      this.isLoading = false
    },
    // 显示地址选择
    showAreaSelect(val) {
      console.log(val)
      const self = this
      self.animated = 'slideIn'
      self.AreaSelect = val
      setTimeout(() => {
        self.animated = ''
        ModalHelper.afterOpen()
      }, 300)
    },
    // 关闭地址选择
    closeAreaSelect(val) {
      const self = this
      self.animated = 'slideOut'
      setTimeout(() => {
        self.AreaSelect = val
        self.animated = ''
        ModalHelper.beforeClose()
      }, 300)
    },
    // 选择城市回调
    selCity(item) {
      console.log(item)
			this.recommendCondition.selectCityId = item.ID
      if (this.locationCity.ID !== item.ID) {
        this.locationCity.ID = item.ID
        this.locationCity.Name = item.Name
        // 手动选择城市后不再进行定位初始化
        const _str = JSON.stringify(item)
        localStorage.setItem('SelectCity', _str)
        this.locationInit = true
        this.listLoad = true
        this.recommendCondition.areaId = item.ID
        this.onRefresh()
      }
    },
    // 关键字搜索商户列表
    search(key) {
      this.recommendCondition.PageIndex = 1
      this.recommendCondition.searchKey = key
      this.artificerList = []
      this.GetStorePage()
    },

    // 获取缓存定位
    getLocalPosition() {

    },
    // 监听定位
    getCurrentPosition(cityName) {
      const _this = this
      // 对查询条件经纬度赋值0 0
      delete _this.recommendCondition.Lng
      delete _this.recommendCondition.Lat

      _this.locationCity.Name = cityName || '定位中...'
      _this.locationInit = !!cityName
      console.log(_this.locationInit)
      this.$toast.loading({
        forbidClick: true,
        message: 'loading...',
        loadingType: 'spinner',
        duration: 0
      })
      _this.$geolocation.getCurrentPosition(function(status, result) {
        if (status === 'complete') {
          _this.onComplete(result)
        } else {
          _this.onError(result)
        }
      })
    },

    // 精准定位成功
    onComplete(data) {
      console.log('精准定位成功')
      console.log(data,"选择地区")
      localStorage.setItem('GeolocationData', JSON.stringify(data))
      this.$toast.clear()
      this.closeAreaSelect(false)
      // 对查询条件经纬度赋值
      this.recommendCondition.Lng = data.position.lng
      this.recommendCondition.Lat = data.position.lat
      if (!this.locationInit) {
        this.locationCity.Name = data.addressComponent.district || data.addressComponent.city
        const adcode = parseInt(data.addressComponent.adcode.substr(0, 4) + '00').toString()
        this.GetCityIdByCode(adcode)
      } else {
        this.listLoad = true
        this.isRefresh = true
        this.onRefresh()
      }
    },
    // 精准定位失败
    onError(data) {
      console.log('精准定位失败')
      const _this = this
      _this.$geolocation.getCityInfo(function(status, result) {
        if (status === 'complete') {
          _this.onComplete1(result)
        } else {
          _this.onError1(result)
        }
      })
    },
    // ip定位成功
    onComplete1(data) {
      console.log('ip定位成功')
      console.log(data,"地区")
			this.recommendCondition.adcode = data.adcode
			this.recommendCondition.selectCityId = 0
      localStorage.setItem('GeolocationData', JSON.stringify(data))
      this.$toast.clear()
      this.closeAreaSelect(false)
      // 对查询条件经纬度赋值
      this.recommendCondition.Lng = data.center[0]
      this.recommendCondition.Lat = data.center[1]
      // 第一次初始化定位城市
      if (!this.locationInit) {
        this.locationCity.Name = data.city
        const adcode = parseInt(data.adcode.substr(0, 4) + '00').toString()
        this.GetCityIdByCode(adcode)
      } else {
        this.listLoad = true
        this.isRefresh = true
        this.onRefresh()
      }
    },
    // ip定位失败
    onError1(data) {
      console.log('ip定位失败')
      console.log(data)
      this.$toast.clear()
      this.$toast.fail({
        message: '获取定位信息失败，请刷新',
        icon: 'close'
      })
      this.locationCity.Name = '未知'
      setTimeout(() => {
        if (!this.locationInit) {
          this.locationInit = true
          this.listLoad = true
          this.isRefresh = true
          this.onRefresh()
        }
      }, 1000)
    },
    

    //排序
		tabChange(e){
			console.log('e',e)
			this.state = e
			this.tabsIndex = e
			this.recommendCondition.orderBy = e + 1
			this.artificerList = []
			this.GetStorePage()
		},
    // 获取技师分页
    GetStorePage() {
			// if(!this.recommendCondition.Lng){
			// 	this.$toast({
			// 		message: '请先定位地址',
			// 		duration: 2000
			// 	})
			// 	return
			// }
			this.recommendCondition.selectCityId = this.recommendCondition.areaId
      // delete this.recommendCondition.Lng
      // delete this.recommendCondition.Lat
			this.recommendCondition.areaId = 0
			this.recommendCondition.selectCityId = 0

      GetArtificerPage(this.recommendCondition).then(res => {				
        if (res) {				
					if (this.recommendCondition.PageIndex >= res.Data.TotalAmout) {
            this.finished = true
					} else {
						this.finished = false
					}
          this.isLoading = false
          if (res.Data && res.Data.Data && res.Data.Data.length > 0) {
            res.Data.Data.forEach(tem => {
							tem.Photos = tem.Photo.split(',')
              if (!tem.Logo && tem.Photo) {
                tem.Photo = tem.Photo.split(',')[0]
              }							
							if(tem.NextBookTime != ''){			
								let booktime = tem.NextBookTime.split(' ')[1]
								tem.NextBookTime = booktime.split(':')[0] + ":" + booktime.split(':')[1]
							}
							tem.StarLevel = Math.round(tem.StarLevel)
              this.artificerList.push(tem)
            })
          }
          this.totalAmout = res.Data.TotalAmout
          this.scollRequest = true
          this.listLoad = true
        }else{
					this.isLoading = false
				}
      })
    },
    // 获取城市id
    GetCityIdByCode(code) {
      GetCityIdByCode({ RegionCode: code }).then(res => {
        if (res) {
          this.locationCity.ID = res.Data

          this.recommendCondition.areaId = res.Data
          const _str = JSON.stringify(this.locationCity)
          localStorage.setItem('SelectCity', _str)
          // 初始化请求参数
          this.recommendCondition.PageIndex = 1
          this.artificerList = []
          // 获取商家列表
          this.GetStorePage()
        }
      })
    },
    // 获取所属区域
    GetUserCityId() {
      GetUserCityId().then(res => {
        if (res && res.Data) {
          if (res.Data.ID === 0) {
            this.getCurrentPosition()
          } else {
            const _str = JSON.stringify(res.Data)
            localStorage.setItem('SelectCity', _str)
            this.getPosition()
          }
        }
      })
    },
    // 滚动事件触发下拉加载
    onScroll() {
      const _this = this
      if (_this.scollRequest === true) {
        if (_this.$utils.getScrollHeight() - _this.$utils.getClientHeight() - _this.$utils.getScrollTop() <= 5) {
          _this.scollRequest = false
          if (_this.recommendCondition.PageIndex < _this.totalAmout) {
            _this.recommendCondition.PageIndex++
            _this.GetStorePage()
          } else {
            _this.end = true
          }
          // }
        }
      }
    },
		goStore(id){
			this.$router.push('physioCertificate/' + id)
		},
		goEvaluation(id){
			this.$router.push({
				path: '/physioValuationList',
				query: {
					id: id,
				}
      })
		},
		showPhoto(item){
			this.Photos = item
			this.showPhotos = true
		},
		showAvatar(item){
			this.Avatar = item
			this.showAvatars = true
		}
  }
}
</script>
<style lang="scss" scoped>
.title{
  background: #F2F3FC;
}
.tab{
  div{
    padding-right: 48px;
    font-weight: bold;
    color: #7D8699;
    font-size: 32px;

  }
  .active{
    font-size: 36px;
    color: #2A2D33;
  }
}
.index-type {
  background: $colorBg;
}
.index-type-item {
  width: 20%;
  .van-image {
    width: 56px;
    height: 56px;
  }
}
.van-hairline--bottom::after {
  border-bottom: none;
}
/deep/.van-dropdown-menu__title .van-ellipsis {
  max-width: 70px;
  font-size: 13px;
}
.avars{
	width: 144px;
	height: 144px;
	position: relative;
}
.champimg{
	width: 176px;
	height: 176px;
	z-index: 300;
	top: -19px;
	left: -21px;
}
.champion{
	position: absolute;
	width: 74px;
	height: 74px;
	left: -20px;
	top: -20px;
	z-index: 101;
}
.avatar{
	width: 144px;
	height: 144px;
	border-radius: 50%;
	position: absolute;
  top: 0;
}
.avar{
	width: 144px;
	height: 144px;
	border-radius: 50%;
}
.classImg{
	width: 144px;
	height: 144px;
}

.serve{
	width: 108px;
	height: 36px;
	background: #24c373;
	border-radius: 16px 8px 16px 8px;
	text-align: center;
	font-size: 22px;
	color: #fff;
	margin-top: 14px;
}

.physio{
	display: flex;
	justify-content: space-between;
}
.avator{
	display: flex;
	flex-direction: column;
	align-items: center;
}	

.user{
	display: flex;
	align-items: center;
	margin-bottom: 14px;
	.username{
		font-size: 32px;
		color: $black2;
		font-weight: 500;
		font-family: PingFangSC-Medium, PingFang SC;
		margin-right: 8px;
		width: 140px;
    overflow: hidden;
    text-overflow: -o-ellipsis-lastline;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    line-clamp: 1;
    -webkit-box-orient: vertical;
	}
	img{
		margin-right: 8px;
		width: 32px;
	}
	.lifephoto{
		height: 32px;
		line-height: 32px;
		background: #F2F3FC;
		border-radius: 4px;
		font-size: 20px;
		font-weight: 400;
		color: #545965;
		padding: 0 8px;
	}
}
.storemsg{
	margin-top: 14px;
	display: flex;
  align-items: center;
	margin-bottom: 14px;
	img{
		margin-right: 4px;
		width: 24px;
	}
	.storename{
		margin-right: 64px;
	}
}
.evanum{
	display: flex;
	align-items: center;
}
.markorder{
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}
.restime{
	display: flex;
	flex-direction: column;
	align-items: center;
	background: #F2F3FC;
	border-top: 2px solid #24c373;
	.reducible{
		font-size: 20px;
		margin-top: 4px;
	}
	.time{
		font-size: 28px;
	}
}
.btn{
	height: 54px;
	line-height: 54px;
	background: #24c373;
	border-radius: 26px;
	color: #fff;
	font-size: 26px;
	padding: 0 24px;
  white-space: nowrap;
}
.unserve{
	background: #F2F3FC;
	color: #333;
}
.address{
	display: flex;
	align-items: center;
	color:#24c373;
	img{
		width: 24px;
	}
}
.usermsg{
	margin-left: 24px;
	margin-right: 16px;
}
.data-empty{
	text-align: center;
	.img{
		width: 400px;
		height: 300px;
	}
	.text{
		font-size: 28px;
		color: $color6;
	}
}

.photos{
	width: 100%;
}
.shop-bg-box{
	width: 100%;
}
.popup-close {
	position: absolute;
	right: 30px;
	top: 30px;
	z-index: 105;
}
.item-icon{
	width: 24px;
	height: 26px;
}
</style>
